<template>
  <!-- 设置自动弹出时间段——平日上班时间组件 -->
  <el-row class="usually_box_li" :gutter="8">
    <!-- 星期 -->
    <el-col :span="12" >
      <!-- 星期回显 -->
      <span class="content" v-if="!isEdit" style="margin-left: 10px">{{dataObj.weekDayTitle}}</span>
      <!-- 星期设置 -->
      <el-popover
              v-else
              ref="popover-tree"
              v-model="popoverVisable"
              placement="top"
              @hide="popoverTreeHide"
              visible-arrow="false"
              trigger="click">
        <!-- 星期设置popover触发组件 -->
        <el-input class="tree_input" size="mini" slot="reference" v-model.trim="dataClone.weekDayTitle" @focus="handleInputFocus" readonly></el-input>
        <!-- 星期设置popover树形组件 -->
        <el-tree
                class="a-tree"
                ref="tree"
                node-key="id"
                default-expand-all
                check-on-click-node
                :default-checked-keys="treeCheckBox"
                show-checkbox
                :data="optionData"
                accordion
                :highlight-current="true">
        </el-tree>
      </el-popover>
    </el-col>
    <!-- 上班时间点 -->
    <el-col :span="9">
      <!-- 上班时间点回显 -->
      <span class="content" v-if="!isEdit">{{dataObj.weekTimeTitle}}</span>
      <!-- 上班时间点设置 -->
      <div v-else class="time_edit_box" v-for="(timeLi, index) in dataClone.workTime">
        <!--<div class="time_edit_li">-->
          <!--<el-input class="time_edit_input start_input" size="mini" v-model.trim="timeLi.start" :placeholder="index === 0 ? '如: 09:00' : ''"></el-input>-->
          <!--<el-input class="time_edit_input" size="mini" v-model.trim="timeLi.end"></el-input>-->
        <!--</div>-->
        <el-time-picker
                is-range
                v-model="timeLi.time"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围">
        </el-time-picker>
        <i class="time_edit_btn iconfont" :class="index ? 'icon-zuixiaohua ' : 'icon-zhankai'" @click="todoTimeLi(index)"></i>
      </div>
    </el-col>
    <!-- 操作按钮 -->
    <el-col :span="3">
      <div class="content" v-if="!isEdit">
        <span class="todoBtn update" @click="todoItem('update')">修改</span>
        <span class="todoBtn delete" @click="todoItem('delete')">删除</span>
      </div>
      <div class="content" v-if="isEdit">
        <span class="todoBtn save" @click="todoItem('save')">保存</span>
        <span class="todoBtn cancel" @click="todoItem('cancel')">取消</span>
      </div>
    </el-col>
  </el-row>
</template>
<script>
  import { deepClone, getFormatDateTime } from '@utils/m7Utils.js'
  import bus from '@/store/eventBus'
  export default {
    name: 'addPopUsuallyTimeLi',
    data () {
      return {
        popoverVisable: false,    // 平日上班时间星期popover展示
        optionData: [{            // 平日上班时间星期设置组件默认值
          id: 'all',
          label: '全部',
          children: [ {
            id: '2',
            label: '星期一'
          }, {
            id: '3',
            label: '星期二'
          }, {
            id: '4',
            label: '星期三'
          }, {
            id: '5',
            label: '星期四'
          }, {
            id: '6',
            label: '星期五'
          }, {
            id: '7',
            label: '星期六'
          }, {            //  getDay()方法返回值是从0（周日）开始，为避免0，因此周日从1开始
            id: '1',
            label: '星期日'
          }]
        }],
        currentTodo: 'add',     // 当前操作（'add' || 'edit'）点击取消和保存按钮的时候用到
        dataObj: {              //  默认参数
          weekDayId: [],          //  星期的id【1,2,3】
          weekDayTitle: '',       //  表格中展示的文案
          workTime: [{time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]}],   //  上班时间点
          weekTimeTitle: ''       //  上班时间点展示文案
        },
        dataClone: {            //  克隆的参数，暂存用到
          weekDayId: [],
          weekDayTitle: '',
          workTime: [{time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]}],
          weekTimeTitle: ''
        },
        treeCheckBox: []   // 默认选中的节点，回显选中的时候用到
      }
    },
    props: {
      data: {           //  当前编辑的数据
        type: Object,
        default: function () {
          return {
            weekDayId: [],
            weekDayTitle: '',
            workTime: [{time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]}],
            weekTimeTitle: ''
          }
        }
      },
      //  随机数，监听更新数据
      random: {
        type: Number,
        default: function () {
          return 0
        }
      },
      curIndex: {         //  当前编辑数据的下标
        type: Number,
        default: function () {
          return 0
        }
      },
      allArray: {       //  所有平日上班时间的数据
        type: Array,
        default: function () {
          return []
        }
      },
      isEdit: {       //  当前是否在编辑数据
        type: Boolean,
        default: function () {
          return false
        }
      }
    },
    watch: {
      random () {
        this.dataObj = deepClone(this.data)
      }
    },
    methods: {
      todoItem (type) {       //  增、删、改和取消操作
        let self = this
        let timeArr = []
        if (type === 'update') {
          //  修改数据
          self.currentTodo = 'update'
          let clone = deepClone(self.dataObj)
          clone.workTime.forEach((item, index) => {   //  上班时间点校验
            //  设置开始时间和结束时间数据设置回显
            let startTime = '2018-12-18 ' + item.start
            let endTime = '2018-12-18 ' + item.end
            timeArr.push({time: [new Date(startTime), new Date(endTime)]})
          })
          clone.workTime = timeArr
          self.dataClone = clone
          bus.$emit('changeIsEdit', {index: self.curIndex, data: true, type: 'usually'})
          self.handleInputFocus()
        } else if (type === 'delete') {
          //  删除数据
          this.$confirm('确定要删除该项吗？', this.$t('public.tip'), {
            confirmButtonText: this.$t('public.confirm'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          }).then(() => {
            bus.$emit('deleteLi', {index: self.curIndex, type: 'usually'})
          })
        } else if (type === 'save') {
//          保存数据
          self.popoverTreeHide()      //  保存之前获取一次星期的数据（特殊情况：选择完成日期之后，直接点击保存按钮，导致保存事件先行触发）
          if (!self.dataClone.weekDayTitle) {     //  星期组件必填校验
            self.$message.error('请选择星期')
            return
          }
          let lengthFlag = false
          let timeTitle = ''
          let coincideFlag = false
          self.dataClone.workTime.forEach((item, index) => {   //  上班时间点校验
            //  设置开始时间和结束时间
            if (!item.time || !item.time.length) {
              lengthFlag = true
              return false
            }
            if (coincideFlag) {
              return false
            }
            let start = getFormatDateTime(item.time[0]).split(' ')[1]
            let end = getFormatDateTime(item.time[1]).split(' ')[1]
            timeTitle += start + '-' + end + ', '
            self.dataClone.workTime.forEach((itemNew, indexNew) => {
              if (indexNew > index) {
                let startNew = getFormatDateTime(itemNew.time[0]).split(' ')[1]
                let endNew = getFormatDateTime(itemNew.time[1]).split(' ')[1]
                if (!(end < startNew || start > endNew)) {
                  coincideFlag = true
                }
              }
            })
            timeArr.push({start: start, end: end})
          })
          if (lengthFlag) {
            self.$message.error('请选择上班时间点')
            return
          }
          if (coincideFlag) {
            self.$message.error('上班时间点有重复时间，请核查')
            return
          }
//          自动弹出时间，时间不可有交集，不可重复
          let repeatFlag = false
          if (self.allArray.length) {
            self.allArray.forEach((item, index) => {
              if (index !== self.curIndex) {
                let weekFlag = false
//                self.dataClone  当前修改的数据       item.data  其它数据
//                当前数据的日期id存在于其他数据中，即为重合
                self.dataClone.weekDayId.forEach((week) => {
                  if (item.data.weekDayId.indexOf(week) !== -1) {
                    weekFlag = true
                  }
                })
                if (weekFlag) {
                  timeArr.forEach((cloneWork) => {
                    item.data.workTime.forEach((arrWork) => {
//                timeArr  当前修改数据时间点集合       item.data.workTime  其它数据时间点集合
//                当前数据结束 > 其它数据开始   或  当前数据开始  >   其他数据结束   代表没有重合，取反即为重合
                      if (!(cloneWork.end < arrWork.start || cloneWork.start > arrWork.end)) {
                        repeatFlag = true
                      }
                    })
                  })
                }
              }
            })
          }
          if (repeatFlag) {
            self.$message.error('平日上班时间点有重复，请核查')
            return
          }
          self.dataClone.weekTimeTitle = timeTitle.slice(0, timeTitle.length - 2)       //  星期数据回显值
          self.dataClone.workTime = timeArr
          bus.$emit('saveLi', {index: self.curIndex, data: self.dataClone, type: 'usually'})                // 抛出数据
          self.dataObj = deepClone(self.dataClone)                                      // 本地保存数据
          self.popoverVisable = false
        } else if (type === 'cancel') {
          //  取消增加||修改
          if (self.currentTodo === 'add') {
            bus.$emit('deleteLi', {index: self.curIndex, type: 'usually', todoType: 'add'})
          } else if (self.currentTodo === 'update') {
            bus.$emit('changeIsEdit', {index: self.curIndex, data: false, type: 'usually'})
            self.dataClone = {        //  克隆数据初始化
              weekDayId: [],
              weekDayTitle: '',
              workTime: [{time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]}],
              weekTimeTitle: ''
            }
          }
        }
      },
      popoverTreeHide () {
        //  星期组件popover隐藏的时候触发
        let self = this
        let arr = self.$refs.tree.getCheckedNodes()     //  获取当前属性组件的值
        let title = ''
        let arrId = []
        arr.forEach(item => {         //  设置title和数组的值
          if (item.id !== 'all') {
            title += item.label + ','
            arrId.push(item.id)
          }
        })
        self.$set(self.dataClone, 'weekDayTitle', title.slice(0, title.length - 1))
        self.$set(self.dataClone, 'weekDayId', arrId)
      },
      handleInputFocus () {
        //  星期组件的input框获取焦点时触发，设置树形组件默认选中值
        let self = this
        self.treeCheckBox = deepClone(self.dataClone.weekDayId)
      },
      todoTimeLi (index) {
        //  上班时间点添加按钮和删除按钮
        if (index === 0) {
          this.dataClone.workTime.push({time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]})
        } else {
          this.dataClone.workTime.splice(index, 1)
        }
      }
    },
    components: {
      bus
    },
    beforeMount () {
      this.dataObj = deepClone(this.data)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .content
    margin-left 2px
  .todoBtn
    cursor pointer
    margin-right 10px
    color $cf-color1
  .todoBtn.cancel
    color $cf-gray6
  .todoBtn.delete
    color $c-pink
  .tree_input
    input
      width calc(100% - 20px)
      margin-left 10px
  .time_edit_li
    width calc(100% - 14px)
    display inline-block
  .time_edit_input
    width calc(50% - 12px)
    display inline-block
  .time_edit_btn
    cursor pointer
    font-size 12px
    color $cf-color1
    margin-left 6px
  .usually_box_li
    border-bottom 1px solid #E7E7EB
  .usually_box_li:last-child
    border none
  .start_input
    position relative
    margin 0 18px 0 10px
    &:before
      content: ''
      border-top 2px solid $c-border2
      width 10px
      position absolute
      top 18px
      right -14px
  .start_input:nth-child(1)
    margin-left 0
</style>
